/*
 * customer产品创建
 * @Author: ljb
 * @Date: 2018-03-27 17:53:51
 * @Last Modified by: ljb
 * @Last Modified time: 2019-01-30 11:33:27
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
	@deep: ~'>>>';
    .v-customer-product-create {
      overflow-y: scroll;

      &::-webkit-scrollbar {
        display: none;
      }

      .product-form {
        width: 520px;
      }

      @{deep} .ivu-icon-plus-round,
      @{deep} .ivu-icon-refresh {
        line-height: 32px;
        margin-right: 5px;
        color: #80848f;
      }
    }
</style>
<style lang="less" rel="stylesheet/less" type="text/less">
    .v-customer-product-create{
        .ivu-radio-group {
            margin: 0 0 0 4.16666667%;
        }
        .btn {
            margin-top: 15px;
        }
    }
</style>
<template>
	<div
		:style="{'max-height':formMaxHeight(true)}"
		class="v-customer-product-create">

		<!-- <Row v-if="Number(getUserInfo.has_youzan) === 1">
			<i-col push="2">
				<Button
					type="primary"
					@click="$emit('syncSale')">
					{{ $t('product.sync_youzan_sale') }}
				</Button>

				<Button
					type="ghost"
					style="margin-left: 8px"
					@click="$emit('syncInventory')">
					{{ $t('product.sync_youzan_inven') }}
				</Button>
			</i-col>
		</Row> -->

		<br>

		<Row
			type="flex"
			justify="start">
			<i-col push="1">
				<Form
					ref="formValidate"
					:model="formValidate"
					:rules="ruleValidate"
					:label-width="labelWidth(110, 120)"
					class="product-form">
					<!-- 类别 -->
					<Form-item
						:label="$t('product.category')"
						prop="category_id">
						<Row>
							<i-col span="16">
								<Select
									v-model="formValidate.category_id"
									clearable
									@on-change="changeCategory"
									@on-clear="clearCategory">
									<OptionGroup
										v-for="(item,key) in groupCategories"
										:key="key"
										:label="item.custom_type_name">
										<Option
											v-for="(value,key) in item.categories"
											:value="value.id"
											:key="key">{{ value.name }}</Option>
									</OptionGroup>
								</Select>
							</i-col>
						</Row>
					</Form-item>
					<!-- 标题 -->
					<Form-item
						:label="$t('product.title')"
						prop="title">
						<Row>
							<i-col span="16">
								<i-input
									v-model="formValidate.title"
									:placeholder="$t('product.please_enter_title')"
									type="text"/>
							</i-col>
						</Row>
					</Form-item>
					<!-- 简称 -->
					<Form-item
						:label="$t('product.name')"
						prop="name">
						<Row>
							<i-col span="16">
								<i-input
									v-model="formValidate.name"
									:placeholder="$t('product.please_enter_name')"
									type="text"/>
							</i-col>
						</Row>
					</Form-item>
					<!-- 编码 -->
					<Form-item
						:label="$t('product.code')"
						prop="spu_code">
						<Row>
							<i-col span="16">
								<i-input
									v-model="formValidate.spu_code"
									:placeholder="$t('product.please_enter_code')"
									type="text"/>
							</i-col>
						</Row>
					</Form-item>
					<!-- 品牌 -->
					<Form-item
						:label="$t('product.brand')"
						prop="brand_id">
						<Row>
							<i-col span="16">
								<Select
									v-model="formValidate.brand_id"
									:clearable="true"
									@on-change="changeBrans">
									<Option
										v-for="( name , key ) in brands"
										:value="key + ''"
										:key="key">{{ name }}</Option>
								</Select>
							</i-col>
							<i-col
								offset="1"
								span="7">
								<Tooltip
									:content="$t('product.refresh')"
									placement="top">
									<a
										href="JavaScript:void(0)"
										@click="refreshAndReset">
										<Icon
											:size="18"
											type="refresh"/>
									</a>
								</Tooltip>
								<Tooltip
									:content="$t('product.add_brand')"
									placement="top">
									<a
										href="JavaScript:void(0)"
										@click="openNewPage('#/customer/product-brand')">
										<Icon
											:size="18"
											type="plus-round"/>
									</a>
								</Tooltip>
							</i-col>
						</Row>
					</Form-item>
					<!-- 系列 -->
					<Form-item
						v-show="has_assets"
						:label="$t('product.series')"
						:prop="has_assets ? 'series' : ''">
						<Row>
							<i-col span="16">
								<Select
									v-model="formValidate.series"
									clearable
									transfer>
									<Option
										v-for="(item) in seriesOptions"
										:value="String(item.id)"
										:key="item.id">{{ item.name }}</Option>
								</Select>
							</i-col>
							<i-col
								offset="1"
								span="7">
								<Tooltip
									:content="$t('product.refresh')"
									placement="top">
									<a
										href="JavaScript:void(0)"
										@click="refreshAndReset">
										<Icon
											:size="18"
											type="refresh"/>
									</a>
								</Tooltip>
								<Tooltip
									:content="$t('product.add_series')"
									placement="top">
									<a
										href="JavaScript:void(0)"
										@click="openNewPage('#/customer/brand-series')">
										<Icon
											:size="18"
											type="plus-round"/>
									</a>
								</Tooltip>
							</i-col>
						</Row>
					</Form-item>

					<Form-item
						v-if="!has_assets"
						:label="$t('product.tag')"
						prop="product_tag_ids">
						<Row>
							<i-col span="16">
								<Select
									v-model="formValidate.product_tag_ids"
									multiple
									clearable
									filterable
									transfer>
									<Option
										v-for="( value , key ) in productTags"
										:value="key+ ''"
										:key="key">{{ value }}</Option>
								</Select>
							</i-col>
						</Row>
					</Form-item>
					<!-- 身体部位 -->
					<!-- <Form-item
						v-if="!has_assets"
						:label="$t('product.body_positions')"
						prop="body_position_ids">
						<Row>
							<i-col span="16">
								<Select
									v-model="formValidate.body_position_ids"
									:placeholder="$t('product.body_positions')"
									clearable
									multiple
									transfer>
									<Option
										v-for="( item , key ) in positions"
										:value="item.id"
										:key="key">{{ item.name }}
									</Option>
								</Select>
							</i-col>
						</Row>
					</Form-item> -->
					<!-- 性别 -->
					<Form-item
						v-show="!has_assets"
						:label="$t('product.gender')"
						prop="stock">
						<RadioGroup v-model="formValidate.sex">
							<Radio :label="0">{{ $t('product.general') }}</Radio>
							<Radio :label="1">{{ $t('product.male') }}</Radio>
							<Radio :label="2">{{ $t('product.female') }}</Radio>
						</RadioGroup>
					</Form-item>
					<!-- 产品价格 -->
					<Form-item
						:label="$t('product.sell_price')"
						prop="sell_price">
						<InputNumber
							:min="0"
							:max="100000000"
							v-model="formValidate.sell_price"
							:placeholder="$t('product.please_enter_sell_price')"/>
					</Form-item>
					<!-- 划线价 -->
					<Form-item
						:label="$t('product.market_price')"
						prop="market_price">
						<InputNumber
							:min="0"
							:max="100000000"
							v-model="formValidate.market_price"
							:placeholder="$t('product.please_enter_market_price')"/>
					</Form-item>
					<!-- 优先级 -->
					<Form-item
						:label="$t('product.priority')"
						prop="priority">
						<InputNumber
							:max="100000"
							:min="0"
							v-model="formValidate.priority"
							:placeholder="$t('product.please_enter_priority')"/>
					</Form-item>
					<!-- 模型文件 -->
					<Form-item
						v-show="has_assets"
						:label="$t('product.model_file')"
						prop="asset_id">
						<Row>
							<i-col span="16">
								<Select
									v-model="formValidate.asset_id"
									:placeholder="$t('product.no_model')"
									clearable
									transfer>
									<Option
										v-for="model in models"
										:value="String(model.id)"
										:key="model.id">{{ model.code }}</Option>
								</Select>
							</i-col>
							<i-col
								offset="1"
								span="7">
								<Tooltip
									:content="$t('product.refresh')"
									placement="top">
									<a
										href="JavaScript:void(0)"
										@click="refreshAndReset">
										<Icon
											:size="18"
											type="refresh"/>
									</a>
								</Tooltip>
								<Tooltip
									:content="$t('product.add_asset')"
									placement="top">
									<a
										href="JavaScript:void(0)"
										@click="openNewPage('#/customer/tryon-material')">
										<Icon
											:size="18"
											type="plus-round"/>
									</a>
								</Tooltip>
							</i-col>
						</Row>
					</Form-item>
					<!-- 商品链接类型 -->
					<Form-item
						:label="$t('product.tb_link_type')"
						prop="product_url_type_id">
						<Row>
							<i-col span="16">
								<Select
									v-model="formValidate.product_url_type_id"
									clearable
									filterable>
									<Option
										v-for="chain in outerChain"
										:value="chain.id + ''"
										:key="chain.id">{{ chain.name }}</Option>
								</Select>
							</i-col>
						</Row>
					</Form-item>
					<!-- 商品链接 -->
					<Form-item
						v-if="formValidate.product_url_type_id"
						:label="$t('product.tb_product_link')"
						:rules="[
							{
								required: true,
								message: $t('validate.required', { field: (productUrlType + $t('product.tb_product_link')) }),
								trigger: 'blur,change',
							},
							{
								type: 'url',
								message: $t('validate.url', { field: (productUrlType + $t('product.tb_product_link')) }),
								trigger: 'blur,change',
							},
						]"
						prop="product_url">
						<Row>
							<i-col span="16">
								<i-input
									v-model="formValidate.product_url"
									:placeholder="$t('product.please_enter_tb_link')"
									type="text"/>
							</i-col>
						</Row>
					</Form-item>
					<!-- 缩略图 -->
					<Form-item
						:label="$t('product.thumb')"
						prop="thumb">
						<Uploader
							ref="thumb"
							@on-remove="(file)=>{handleRemove('thumb',file)}"
							@on-change="(file)=>{handleChange('thumb',file)}">
							{{ $t('product.img_tip') }}
						</Uploader>
					</Form-item>
					<!-- 颜色缩略图 -->
					<Form-item
						v-show="has_assets"
						:label="$t('product.color_thumb')"
						prop="color_thumb">
						<Uploader
							ref="color_thumb"
							@on-remove="(file)=>{handleRemove('color_thumb',file)}"
							@on-change="(file)=>{handleChange('color_thumb',file)}">
							{{ $t('product.img_tip') }}
						</Uploader>
					</Form-item>

					<Form-item>
						<Button
							type="primary"
							@click="handleSubmit('formValidate')">
							{{ $t('common.submit') }}
						</Button>

						<Button
							type="ghost"
							style="margin-left: 8px"
							@click="handleReset('formValidate')">
							{{ $t('common.reset') }}
						</Button>
					</Form-item>

				</Form>
			</i-col>
		</Row>
	</div>
</template>

<script>

import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import { computedFormMaxHeight } from 'src/views/mixins/computedFormMaxHeight';
import { validateImage, validateUpdateImage } from 'src/validate'; // 引入校验文件
import Uploader from 'src/views/component/Uploader';
import { mapGetters } from 'vuex';
import { getVisibilityChangeEventName, getVisibilityState } from 'src/utils/helper';

export default {
	name: 'ProductCreate',
	components: {
		Uploader,
	},
	mixins: [labelWidthMixin, computedFormMaxHeight],
	props: {
		brands: {
			type: [Object, Array],
			required: true,
		},
		groupBrands: {
			type: Array,
			default() {
				return [];
			},
		},
		outerChain: {
			type: Array,
			default() {
				return [];
			},
		},
		categories: {
			type: Array,
			default() {
				return [];
			},
		},
		groupCategories: {
			type: Array,
			default() {
				return [];
			},
		},
		productTags: {
			type: Object,
			default() {
				return {};
			},
		},
		modelsGroup: {
			type: Array,
			default() {
				return [];
			},
		},
		loading: {
			type: Boolean,
			default() {
				return false;
			},
		},
		// positions: {
		// 	type: Array,
		// 	default() {
		// 		return [];
		// 	},
		// },
		cosmeticMaterials: {
			type: Array,
			default() {
				return [];
			},
		},
		refresh: {
			type: Function,
			required: true,
		},
	},

	data() {
		return {
			formValidate: {
				category_id: '', // 类别

				title: '', // 标题

				name: '', // 简称

				spu_code: '', // 编码

				brand_id: '', // 品牌

				series: '', // 系列

				material: '', // 材质

				product_mod_id: 0,

				product_tag_ids: [], // 标签

				// body_position_ids: [], // 身体部位

				sex: 0, // 性别

				asset_id: '', // 模型文件

				sell_price: 0, // 产品价格

				market_price: 0, // 划线价

				priority: 0, // 优先级

				product_url_type_id: '', // 商品链接类型

				product_url: '', // 商品链接

				thumb: null, // 缩略图

				color_thumb: null, // 颜色缩略图
			}, // 新建产品时的表单

			models: [], // 模型文件

			ruleValidate: { // 表单验证规则
				product_url_type_id: [
					{
						message: this.$t('validate.required', { field: this.$t('product.tb_link_type') }),
						trigger: 'blur,change',
					},
				],
				product_url: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.tb_product_link') }),
						trigger: 'blur,change',
					},
					{
						type: 'url',
						message: this.$t('validate.url', { field: this.$t('product.tb_product_link') }),
						trigger: 'blur,change',
					},
				],
				category_id: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.category') }),
						trigger: 'blur,change',
					},
				],
				brand_id: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.brand') }),
						trigger: 'blur,change',
					},
				],
				series: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.series') }),
						trigger: 'blur,change',
					},
				],
				material: [
					{
						message: this.$t('validate.required', { field: this.$t('product.material') }),
						trigger: 'blur,change',
					},
				],
				product_tag_ids: [
					{
						required: true,
						type: 'array',
						message: this.$t('validate.required', { field: this.$t('product.tag') }),
						trigger: 'blur,change',
					},
				],
				// body_position_ids: [
				// 	{
				// 		required: true,
				// 		type: 'array',
				// 		message: this.$t('validate.required', { field: this.$t('product.body_positions') }),
				// 		trigger: 'blur,change',
				// 	},
				// ],
				asset_id: [
					{
						message: this.$t('validate.required', { field: this.$t('product.model_file') }),
						trigger: 'blur,change',
					},
				],
				title: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.title') }),
						trigger: 'blur,change',
					},
				],
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.name') }),
						trigger: 'blur,change',
					},
				],
				spu_code: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.code') }),
						trigger: 'blur,change',
					},
				],
				market_price: [
					{
						// required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.market_price') }),
						trigger: 'blur,change',
					},
				],
				sell_price: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.sell_price') }),
						trigger: 'blur,change',
					},
				],
				priority: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.priority') }),
						trigger: 'blur,change',
					},
				],
				thumb: [
					{
						required: true,
						validator: validateImage,
						trigger: 'blur,change',
					},
				],
				color_thumb: [
					{
						validator: validateUpdateImage,
						trigger: 'blur,change',
					},
				],
			},

			has_assets: true, // 是否关联素材

			// brandList: [], // 系列信息
		};
	},

	computed: {
		...mapGetters('userToken', [
			'getUserInfo',
		]),
		// 产品类型的name值
		productUrlType() {
			const { product_url_type_id } = this.formValidate;
			const selected_type = this.outerChain.filter(chain => parseInt(chain.id, 10) === parseInt(product_url_type_id, 10))[0];

			return selected_type.name || '';
		},

		seriesOptions() {
			if (this.formValidate.brand_id) {
				const [brand] = this.groupBrands.filter(item => item.id.toString() === this.formValidate.brand_id);
				return brand ? brand.brand_series : [];
			}
			return [];
		},
	},
	mounted() {
		this.listenVisibilityChange();
	},
	destroyed() {
		this.removeVisibilityChangeListener();
	},
	methods: {

		/**
		 * 监听页面状态
		 */
		listenVisibilityChange() {
			const visibilitychange = getVisibilityChangeEventName();
			if (visibilitychange) {
				document.addEventListener(visibilitychange, this.handleVisibilityChange, false);
			}
		},

		/**
		 * 处理页面 Visibility change 事件
		 */
		handleVisibilityChange() {
			// 由于 Create 和 edit组件都监听了VisibilityChange 事件, 避免多次刷新;
			const isFromCreate = sessionStorage.getItem('from') === 'create';
			const isAdded = sessionStorage.getItem('added-data');
			if (document[getVisibilityState()] === 'visible' && isAdded && isFromCreate) {
				this.refreshAndReset();
				sessionStorage.setItem('added-data', '');
			}
		},

		/**
		 * 移除监听器
		 */
		removeVisibilityChangeListener() {
			const visibilitychange = getVisibilityChangeEventName();
			if (visibilitychange) {
				document.removeEventListener(visibilitychange, this.handleVisibilityChange);
			}
		},

		/**
		 * 处理点击刷新icon事件
		 * 当前版本2.13 会出现 select 数据改变(属性key绑定的值不变的情况) option 组件视图不会发生改变
		 * 因此在刷新的时候首先在 views 中清空select数据, 可触发select组件重新渲染. 然后重置select组件的v-model值
		 * @link https://github.com/iview/iview/issues/3574#event-1623895643
		 * @link https://jsfiddle.net/91b3oes8/
		 */
		refreshAndReset() {
			const {
				brand_id = '', series = '', material = '',
			} = this.formValidate;
			this.refresh()
				.then(() => {
					this.formValidate.brand_id = (brand_id in this.brands) ? brand_id : '';
					const [isInCosmeticMaterials] = this.cosmeticMaterials.filter(item => item.id.toString() === material);
					this.formValidate.material = isInCosmeticMaterials ? material : '';
					this.$nextTick(() => {
						const [isInSeries] = this.seriesOptions.filter(item => item.id.toString() === series);
						this.formValidate.series = isInSeries ? series : '';
					});
					this.changeCategory(this.formValidate.category_id);
				});
		},

		/**
		 * 打开新的页面
		 */
		openNewPage(hash) {
			sessionStorage.setItem('from', 'create');
			window.open(window.location.pathname + hash);
		},

		/**
		 *改变类型与模型关联文件
		 * @param  {Number} category_id {改变select获取到value值}
		 * @return {undefined}
		 */
		changeCategory(category_id) {
			if (category_id === '') { // 清空
				this.has_assets = true;
				this.resetTagAndPositionOptions();
				this.formValidate.series = '';
				return;
			}
			const has_assets = this.hasModelAssets(category_id);
			this.models = this.takeModels(category_id);
			if (has_assets) {
				this.resetTagAndPositionOptions();
			} else { // 没素材是护肤品
				this.formValidate.asset_id = null;
				this.formValidate.series = '';
			}
			this.has_assets = has_assets;
			if (this.has_assets !== has_assets) {
				this.has_assets = has_assets;
			}
		},

		/**
		 *清空类型与模型关联文件
		 * @return {undefined}
		 */
		clearCategory() {
			this.models = [];
		},

		/**
		 * 改变品牌与系列文件
		 * @param {String} brand_id {改变select获取到value值}
		 * @return {undefined}
		 */
		changeBrans() {
			this.formValidate.series = '';
		},

		/**
		 *  重置标签/身体部位选项
		 * @param  {Number} category_id {改变select获取到value值}
		 * @return {undefined}
		 */
		resetTagAndPositionOptions() {
			this.formValidate.product_tag_ids = [];
			// this.formValidate.body_position_ids = [];
		},

		/**
		 *  获取模型
		 *  @param {number} category_id {类型选中的值value}
		 *  @return {array} models
		 */
		takeModels(category_id) {
			let models = [];
			this.modelsGroup.forEach((item) => {
				if (item.category_id === category_id) {
					models = item.assets;
				}
			});
			return models;
		},

		/**
		 * 是否有模型素材
		 * @param {number} category_id {类型选中的值value}
		 * @return {boolean} has_assets
		 */
		hasModelAssets(category_id) {
			const [category] = this.categories.filter(item => item.id === category_id);
			return category && !!category.has_asset;
		},

		/**
		 * 选择图片
		 * @param {Object} file {选择的文件对象集合}
		 * @param {String} field {icon}
		 * @return {undefined}
		 */
		handleChange(field, { file }) {
			this.formValidate[field] = file;
			this.$refs.formValidate.validateField(field);
		},

		/**
		 * 删除图片
		 * @param {String} field {icon}
		 * @return {undefined}
		 */
		handleRemove(field) {
			this.formValidate[field] = null;
			this.$refs.formValidate.validateField(field);
		},

		/**
         * 提交表单
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleSubmit(name) {
			if (this.loading) return;
			// formValidate.body_position_ids
			this.$refs[name].validate((valid) => {
				if (valid) {
					this.$emit('post', this.formDataCreate());
				} else {
					this.$Message.error(this.$t('common.exist_empty_field'));
				}
			});
		},

		/**
         * 重置表单
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleReset(name) {
			this.$refs.thumb.reset();
			this.$refs.color_thumb.reset();
			this.$refs[name].resetFields();
		},

		/**
         * 手动拼接表单数据
         * @return {Object} {拼接好的表单数据}
         */
		formDataCreate() {
			const new_object = {
				category_id: this.formValidate.category_id,

				brand_id: this.formValidate.brand_id,

				product_mod_id: 0,

				title: this.formValidate.title,

				name: this.formValidate.name,

				spu_code: this.formValidate.spu_code,

				market_price: this.formValidate.market_price,

				sell_price: this.formValidate.sell_price,

				priority: this.formValidate.priority,

				thumb: this.formValidate.thumb,
				
				color_thumb: this.formValidate.color_thumb,

				product_url_type_id: this.formValidate.product_url_type_id,

				product_url: this.formValidate.product_url ? this.formValidate.product_url : null,

				asset_id: this.has_assets ? this.formValidate.asset_id : null,

				sex: !this.has_assets ? this.formValidate.sex : null,

				product_tag_ids: !this.has_assets ? this.formValidate.product_tag_ids : null,

				body_position_ids: [],

				cosmetic_material_id: this.formValidate.material ? this.formValidate.material : null,

				brand_series_id: this.formValidate.series ? this.formValidate.series : null,
			};

			const form_data = new FormData();

			Object.keys(this.skipNulls(new_object))
				.forEach((key) => {
					switch (key) {
					case 'product_tag_ids':
						if (new_object[key].length > 0) {
							new_object[key].forEach((tag, index) => {
								form_data.append(`${key}[${index}]`, tag);
							});
						}

						break;
					// case 'body_position_ids':
					// 	if (new_object[key].length > 0) {
					// 		new_object[key].forEach((value, index) => {
					// 			form_data.append(`${key}[${index}]`, value);
					// 		});
					// 	}

						// break;
					default:
						form_data.append(key, new_object[key]);

						break;
					}
				});	

			return form_data;
		},

		/**
		 * 跳过对象中的 null 值元素
		 * @param {Object} source {表单对象集合}
		 * @returns {Object} target
		 */
		skipNulls(source) {
			const target = {};
			Object.keys(source)
				.forEach((key) => {
					const is_null = typeof source[key] === 'object' && !source[key];
					if (!is_null) {
						Object.assign(target, { [key]: source[key] });
					}
				});
			return target;
		},

	},

};
</script>
